package com.xstudio.pvzreborn.entity.entities.plant;

import com.xstudio.pvzreborn.entity.PVZDamageSource;
import com.xstudio.pvzreborn.entity.entities.PVZLivingEntityBase;
import com.xstudio.pvzreborn.entity.entities.plant.api.IAttractablePlant;
import com.xstudio.pvzreborn.event.custom.PVZPlantEvent;
import com.xstudio.pvzreborn.utils.LevelUtils;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import org.jetbrains.annotations.NotNull;

/**
 * @author Bread_NiceCat
 */
public abstract class PVZPlantBase extends PVZLivingEntityBase implements IAttractablePlant {

	/**
	 * 注册一个事件以防止植物叠加在同一格
	 */
	private boolean isRegistered;

	protected PVZPlantBase(EntityType<? extends PVZLivingEntityBase> pEntityType, Level pLevel) {
		super(pEntityType, pLevel);
	}

	public static AttributeSupplier.Builder createPlantAttributes() {
		return createLivingAttributes()
				.add(Attributes.MOVEMENT_SPEED, 0);
	}


	@SubscribeEvent
	public void onOtherPlantPlanting(PVZPlantEvent.PlantPlantedEvent event) {
		if (isRemoved()) {//借力取消订阅自己
			MinecraftForge.EVENT_BUS.unregister(this);
		} else {
			//检测当前自己存在于evt里边的方块Pos
			event.setCanceled(event.getPos().equals(blockPosition().below()));
		}
	}

	@Override
	public boolean hurt(DamageSource pSource, float pAmount) {
		return !(pSource.getEntity() instanceof Player) && super.hurt(pSource, pAmount);
	}

	@Override
	public void tick() {
		super.tick();
		if (!isRegistered) {
			MinecraftForge.EVENT_BUS.register(this);
			isRegistered = true;
		}
		if (LevelUtils.delay(level, 1) && (!level.getBlockState(blockPosition().below()).is(Blocks.GRASS_BLOCK) || !level.getBlockState(blockPosition()).is(Blocks.AIR))) {
			this.hurt(PVZDamageSource.INVALID_ENVIRONMENT, getMaxHealth() / 5);
		}
	}

	@Override
	public void move(@NotNull MoverType pType, @NotNull Vec3 pPos) {
	}

	@Override
	public boolean isNoGravity() {
		return true;
	}

	@Override
	public AttractLevel attractPriority() {
		return AttractLevel.I;
	}
}
